package com.caipos.mqtt.handler;

import com.caipos.mqtt.entity.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class FourGHandler extends BaseSensorDataHandler<MqttData> {

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 解析二代协议包
     * @param mqttData
     * @return
     */
    @Override
    public List<SensorDataDO> analysis(MqttData mqttData) {
        String stationcode = mqttData.getMqttData1Entity().getGwid();
        Integer interval = mqttData.getMqttData1Entity().getInterval();
        Date thattime = mqttData.getThattime();
        List<MqttNodeData> nodelist = mqttData.getMqttData1Entity().getNodelist();
        List<SensorDataDO> list = new ArrayList<>();
        if(nodelist==null||nodelist.size()==0||nodelist.isEmpty()){
            return null;
        }
        for (MqttNodeData nd : nodelist) {
            String nodecode = nd.getNdid();
            for (MqttSensorData sd : nd.getSensordatalist()) {
                String[] chinel = sd.getSsinfo().split("/");
                String sensorcode = nodecode+chinel[0];
                Double senval = Double.parseDouble(sd.getSsvalue()[0]);
                Integer sensormodel = Integer.parseInt(chinel[1]);
                SensorDataDO sdd = new SensorDataDO();
                sdd.setInterval(interval);
                sdd.setNodecode(nodecode);
                sdd.setStationcode(stationcode);
                sdd.setSensorcode(sensorcode);
                sdd.setSensormodel(sensormodel);
                sdd.setSensortype(sensormodel);
                sdd.setSenval(senval);
                sdd.setThattime(thattime);
                list.add(sdd);
                //将待处理的传感数据以list形式存入redis：
//                redisTemplate.opsForHash().put("smart_nodeDataMap", nodecode, list);
            }
        }
        return list;
    }

    /**
     * 将解析过来的有效sensor实时数据存入以sensorcode为key的redis中
     */
    @Override
    public void doDataStore(SensorDataDO sdd) {
        SensorLastData sld=new SensorLastData();
        BeanUtils.copyProperties(sdd, sld);
        sld.setVal_aver(sdd.getSenval());
        sld.setVal_last(sdd.getSenval());
        sld.setVal_min(sdd.getSenval());
        sld.setVal_max(sdd.getSenval());
        sld.setVal_sum(sdd.getSenval());
        sld.setSensor_ch(Integer.parseInt(sdd.getSensorcode().replace(sdd.getNodecode(),"")));
        redisTemplate.opsForValue().set(sdd.getSensorcode(), sld);
    }

    @Override
    boolean isCheckData() {
        return false;
    }

    @Override
    void checkData(SensorDataDO sdd) {
        if("190718B11S0401".equals(sdd.getSensorcode())){
            super.checkData(sdd);
            sdd.setSenval(666.9);
        }
    }
}
